from netCDF4 import Dataset
import datetime

import lbt
from ConnectJDBCToMySql import *
import geojson
from shapely.geometry import Point
import json
import lbt


# 从nc中获取某一个属性的全部值，返回装有json字典对象的List
# 传入值filePath：nc文件路径
def ReadFromNc(filePath, jrsjid1, jrsjid2, jrsjid3):
    try:
        sql4 = "UPDATE tb_jrsj SET jrsj_jxstorestatus = 1 AND jrsj_filestorestatus = 1 WHERE jrsj_id = %s " % (jrsjid1)
        sql5 = "UPDATE tb_jrsj SET jrsj_jxstorestatus = 1 AND jrsj_filestorestatus = 1 WHERE jrsj_id = %s " % (jrsjid2)
        sql6 = "UPDATE tb_jrsj SET jrsj_jxstorestatus = 1 AND jrsj_filestorestatus = 1 WHERE jrsj_id = %s " % (jrsjid3)

        try:
            nc_obj = Dataset(filePath)
            # print('--------------------')
            # print(nc_obj)
            # print('--------------------')
            x = (nc_obj.variables['x'][:])
            y = (nc_obj.variables['y'][:])
            time = (nc_obj.variables['time'][:])
            # 露点温度
            Dewpoint_temperature_height_above_ground = (nc_obj.variables['Dewpoint_temperature_height_above_ground'][:])
            # 相对湿度
            Relative_humidity_height_above_ground = (nc_obj.variables['Relative_humidity_height_above_ground'][:])
            # 温度
            Temperature_height_above_ground = (nc_obj.variables['Temperature_height_above_ground'][:])
            # 1小时累计降水量
            Total_precipitation_surface = (nc_obj.variables['Total_precipitation_surface'][:])
            # 2分钟平均风向
            Wind_direction_from_which_blowing_height_above_ground = (
                nc_obj.variables['Wind_direction_from_which_blowing_height_above_ground'][:])
            # 2分钟平均风速
            Wind_speed_height_above_ground = (nc_obj.variables['Wind_speed_height_above_ground'][:])
            # U风分量
            u_component_of_wind_height_above_ground = (nc_obj.variables['u-component_of_wind_height_above_ground'][:])
            # v风分量
            v_component_of_wind_height_above_ground = (nc_obj.variables['v-component_of_wind_height_above_ground'][:])

            # 获取开始的时间 因为time里面存储是[24,48,...240]  而不是具体的时间
            sinceTimeStr = nc_obj.variables['time'].units.split(" ")[-1]
            sinceTime = datetime.datetime.strptime(sinceTimeStr, '%Y-%m-%dT%H:%M:%SZ')
            # print(sinceTime)

            jsondictList = []
            m = x.shape[0]  # 94
            n = y.shape[0]  # 83
            t = time.shape[0]
            for k in range(t):
                for i in range(m):
                    for j in range(n):
                        Time = (sinceTime + datetime.timedelta(hours=time[k])).strftime("%Y-%m-%d %H:%M:%S")
                        # X坐标值
                        XCoordinate = x[i]
                        # Y坐标值
                        YCoordinate = y[j]
                        # 露点温度
                        LDTem = Dewpoint_temperature_height_above_ground[k, 0, j, i]
                        # 相对湿度
                        Xdsd = Relative_humidity_height_above_ground[k, 0, j, i]
                        # 温度
                        Tem = Temperature_height_above_ground[k, 0, j, i]
                        # 1小时累计降水量
                        JslYxs = Total_precipitation_surface[k, j, i]
                        # 2分钟平均风向
                        WindDirect = Wind_direction_from_which_blowing_height_above_ground[k, 0, j, i]
                        # 2分钟平均风速
                        WindSpeed = Wind_speed_height_above_ground[k, 0, j, i]
                        # U风分量
                        UCom = u_component_of_wind_height_above_ground[k, 0, j, i]
                        # v风分量
                        VCom = v_component_of_wind_height_above_ground[k, 0, j, i]

                        # print("x:"+str(XCoordinate)
                        #       +" y:"+ str(YCoordinate)
                        #       +" 露点温度："+str(LDTem)
                        #       +" 相对湿度："+str(Xdsd)
                        #       +" 温度："+str(Tem)
                        #       +" 1小时累计降水量："+str(JslYxs)
                        #       +" 2分钟平均风向："+str(WindDirect)
                        #       +" 2分钟平均风速："+str(WindSpeed)
                        #       +" U风分量："+ str(UCom)
                        #       +" V风分量："+ str(VCom))

                        NcOneObjectDict = dict()
                        NcOneObjectDict['XCoordinate'] = round(float(XCoordinate), 7)
                        NcOneObjectDict['YCoordinate'] = round(float(YCoordinate), 7)
                        NcOneObjectDict['LDTem'] = round(float(LDTem), 7)
                        NcOneObjectDict['Xdsd'] = round(float(Xdsd), 7)
                        NcOneObjectDict['Tem'] = round(float(Tem), 7)
                        NcOneObjectDict['JslYxs'] = round(float(JslYxs), 7)
                        NcOneObjectDict['WindDirect'] = round(float(WindDirect), 7)
                        NcOneObjectDict['WindSpeed'] = round(float(WindSpeed), 7)
                        NcOneObjectDict['UCom'] = round(float(UCom), 7)
                        NcOneObjectDict['VCom'] = round(float(VCom), 7)
                        geojsonName = ["Xdsd",'Tem','JslYxs','WindDirect','WindSpeed']
                        jsondictList.append(NcOneObjectDict)
                        longitude = lbt.zhuan(XCoordinate,YCoordinate)
                        for geojsonnnnn in geojsonName:
                            point = Point((longitude["lon"], longitude["lat"]))
                            geojsondata = geojson.Feature(geometry=point, properties={
                                "value": NcOneObjectDict[geojsonnnnn]})
                            # 储存geojson到数据库
                            Sqldate = dict()
                            Sqldate["geoJsonTableName"] = geojsonnnnn
                            Sqldate["time"] = sinceTime
                            Sqldate["geojson"] = json.dumps(geojsondata)
                            Sqldate["jrsjid"] = jrsjid1
                            sql7 = INSERT_lapsGeojson(Sqldate)
                            try:
                                c4 = tosql3()
                                c4[1].execute(sql7)
                            except Exception as e:
                                print(f"LapsGeojsonEorro------ {e}")
                            finally:
                                c4[0].close()
                                c4[1].close()

                        # #=============================连接数据库==================================
                        sql1 = "INSERT INTO tb_laps(laps_xcoordinate,laps_ycoordinate,laps_ldtem,laps_xdsd,laps_tem,laps_jslyxs,laps_winddirect,laps_windspeed,laps_ucom,laps_vcom,laps_time,laps_jrsjid) \
                                VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                               (XCoordinate, YCoordinate, LDTem, Xdsd, Tem, JslYxs, WindDirect, WindSpeed, UCom, VCom,
                                Time, jrsjid1)
                        sql2 = "INSERT INTO tb_laps(laps_xcoordinate,laps_ycoordinate,laps_ldtem,laps_xdsd,laps_tem,laps_jslyxs,laps_winddirect,laps_windspeed,laps_ucom,laps_vcom,laps_time,laps_jrsjid) \
                                VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                               (XCoordinate, YCoordinate, LDTem, Xdsd, Tem, JslYxs, WindDirect, WindSpeed, UCom, VCom,
                                Time, jrsjid2)

                        sql3 = "INSERT INTO tb_laps(laps_xcoordinate,laps_ycoordinate,laps_ldtem,laps_xdsd,laps_tem,laps_jslyxs,laps_winddirect,laps_windspeed,laps_ucom,laps_vcom,laps_time,laps_jrsjid) \
                                                        VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                               (XCoordinate, YCoordinate, LDTem, Xdsd, Tem, JslYxs, WindDirect, WindSpeed, UCom, VCom,
                                Time, jrsjid3)

                        try:
                            c1 = tosql1()
                            c1[1].execute(sql1)
                        except Exception as e:
                            print("LAPSNcToJson(1) ----- ")
                        finally:
                            c1[1].close()
                            c1[0].close()

                        try:
                            c2 = tosql2()
                            c2[1].execute(sql2)
                        except Exception as e:
                            print("LAPSNcToJson(2) ----- ")
                        finally:
                            c2[1].close()
                            c2[0].close()

                        try:
                            c3 = tosql3()
                            c3[1].execute(sql3)
                        except Exception as e:
                            print("LAPSNcToJson(2) ----- ")
                        finally:
                            c3[1].close()
                            c3[0].close()


            try:
                c1 = tosql1()
                c1[1].execute(sql4)
            except Exception as e:
                print("LAPSNcToJson(3) ----- ")
            finally:
                c1[1].close()
                c1[0].close()

            try:
                c2 = tosql2()
                c2[1].execute(sql5)
            except Exception as e:
                print("LAPSNcToJson(4) ----- ")
            finally:
                c2[1].close()
                c2[0].close()

            try:
                c3 = tosql3()
                c3[1].execute(sql6)
            except Exception as e:
                print("LAPSNcToJson(6) ----- ")
            finally:
                c3[1].close()
                c3[0].close()

            return jsondictList

        except Exception as e:
            print("LAPSNcToJson 文件解析异常 ----- ")

    except Exception as e:
        print("LAPSNcToJson 数据库连接异常 ----- ")
    finally:
        c1[1].close()
        c1[0].close()
        c2[1].close()
        c2[0].close()
        c3[1].close()
        c3[0].close()


def main(filePath, jrsjid1, jrsjid2, jrsjid3):
    jsondictList = ReadFromNc(filePath, jrsjid1, jrsjid2, jrsjid3)
